package com.yuwen.example.consumer;

/**
 * @ClassNameUserServiceProxy
 * @Description TODO
 * @Author钰玟
 * @Date2025/3/29 下午9:50
 * @Version 1.0
 **/

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.yuwen.example.common.model.User;
import com.yuwen.example.common.service.UserService;
import com.yuwen.yuwenRPC.model.RpcRequest;
import com.yuwen.yuwenRPC.model.RpcResponse;
import com.yuwen.yuwenRPC.serializer.JdkSerializer;
import com.yuwen.yuwenRPC.serializer.Serializer;

import java.io.IOException;

/**
 *
 * userService的代理对象(静态代理)
 */
public class UserServiceProxy implements UserService {
    @Override
    public User getUser(User user) {
        //指定序列化器
        Serializer serializer = new JdkSerializer();

        //封装请求数据
        RpcRequest rpcRequest = RpcRequest
                                    .builder()
                                    .serviceName(UserService.class.getName()) // 服务名
                                    .methodName("getUser")//方法名
                                    .parameterTypes(new Class[] {User.class}) //返回参数类型
                                    .parameters(new Object[] {user})//返回参数
                                    .build();

        try {
            //将请求数据转化为 rpcRequest
            byte[] bytes = serializer.serialize(rpcRequest);
            //结果字节数组
            byte[] result = null;
            try(HttpResponse httpResponse = HttpRequest.post("http://localhost:8080").body(bytes).execute()) {
                result =httpResponse.bodyBytes();
            }
            //封装结果字节数组
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
//            返回数据
            return (User) rpcResponse.getData();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return null;
    }
}
